<template>
  <div class="app-container">
    <el-tabs v-model="activityType" @tab-click="handleClick">
      <el-tab-pane
        v-for="item in menuList"
        :key="item.id"
        :label="item.menuName"
        :name="String(item.id)"
      ></el-tab-pane>
    </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="活动名称" prop="code">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="currentStatus">
        <el-select
          v-model="queryParams.currentStatus"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="onAdd">新增</el-button>
    <el-table v-loading="loading" :data="tableData">
      <el-table-column prop="activityName" label="活动名称"></el-table-column>
      <el-table-column
        prop="activityNo"
        label="活动编号"
        v-if="activityType != 1"
      ></el-table-column>
      <el-table-column
        prop="queuingInstructions"
        label="预约须知"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="activityPlace" label="活动地址"></el-table-column>
      <!-- 添加活动类型列，仅在非互动体验页面显示 -->
      <el-table-column label="三级菜单" v-if="activityType != '1'">
        <template slot-scope="scope">
          {{ getActivityMenuName(scope.row.activityMenuId) }}
        </template>
      </el-table-column>
      <el-table-column prop="createUserName" label="创建人"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间"></el-table-column>
      <el-table-column
        label="状态"
        prop="currentStatus"
        :formatter="statusFormat"
      />
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <Actions
            :row="row"
            @onPublish="onPublish(row)"
            @onOffShelf="onOffShelf"
            @onEdit="onEdit"
            @onDetail="onDetail"
            @onDelete="onDelete"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination :total="pageParams.total" :page.sync="pageParams.pageNum" :limit.sync="pageParams.pageSize"
            @pagination="getPage" /> -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="visible"
      width="70%"
      :destroy-on-close="true"
    >
      <Add
        ref="AddForm"
        @success="onSuccess"
        @cancel="onCancel"
        :activityType="activityType"
      />
    </el-dialog>
    <el-dialog
      title="详情"
      :visible.sync="visibleDetail"
      width="70%"
      :destroy-on-close="true"
    >
      <Detail
        ref="Detail"
        :activityType="activityType"
        @cancel="onCancelDetail"
      />
    </el-dialog>

    <el-dialog
      title="提交一级审核"
      :visible.sync="open2"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form2" label-width="100px">
        <template>
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="默认" name="first">
              <el-select v-model="form2.nextEmp" placeholder="请选择">
                <el-option
                  v-for="item in nextEmpList"
                  :key="item.userId"
                  :label="item.userId + '-' + item.userCnName"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="firstSubmit" type="primary">提交</el-button>
        <el-button @click="open2 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  pageList,
  deleteById,
  listUsers,
  offShelf,
  audit,
} from "@/api/activityConfiguration";
import { getMenuTree, getListByParentId } from "@/api/activityMenu";
import Add from "./add.vue";
import Detail from "./detail.vue";
import { formatCurrStatus } from "./status";
import Actions from "./actions.vue";
export default {
  components: {
    Add,
    Detail,
    Actions,
  },
  data() {
    return {
      formatCurrStatus,
      showSearch: true,
      queryParams: {
        activityName: "",
        activityMenuId: "1",
        currentStatus: null
      },
      // 添加活动菜单列表和缓存
      activityMenuList: [],
      activityMenuCache: {},
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      loading: false,
      tableData: [],
      visible: false,
      dialogTitle: "",
      visibleDetail: false,
      activityType: "1",
      menuList: [],
      statusList: [
        {
          id: "1",
          name: "草稿",
        },
        {
          id: "2",
          name: "待一级审核",
        },
        {
          id: "3",
          name: "待二级审核",
        },
        {
          id: "4",
          name: "待发布",
        },
        {
          id: "5",
          name: "已发布",
        },
      ],
      open2: false,
      form2: {
        id: null,
        nextEmp: null,
      },
      activeName: "first",
      nextEmpList: [],
    };
  },
  created() {
    this.getMenuData();
  },
  mounted() {
    // 初始化活动类型为"活动预约"
    this.initActivityType();
  },
  methods: {
    initActivityType() {
      // 默认选中"活动预约"
      this.activityType = "1";
      this.queryParams.activityMenuId = "1";
    },
    getMenuData() {
      getMenuTree(1).then((res) => {
        if (res.code === 200 && res.data) {
          // 先创建活动预约选项卡
          this.menuList = [{ id: "1", menuName: "互动体验" }];
          
          // 处理后端返回的菜单数据，保持原有ID
          if (res.data && res.data.length > 0) {
            res.data.forEach(item => {
              this.menuList.push({
                id: String(item.id), // 确保ID是字符串类型
                menuName: item.menuName
              });
            });
          }
          
          // 设置默认选中第一个tab
          this.activityType = "1";
          this.queryParams.activityMenuId = "1";
          
          // 获取页面数据
          this.getPage();
        }
      });
    },
    getPage() {
      // 直接使用当前标签页ID作为activityType参数
      const params = {
        ...this.queryParams,
        pageNum: this.pageParams.pageNum,
        pageSize: this.pageParams.pageSize,
        activityType:  this.activityType === "1" ? "1" : "2"
      };
      
      this.loading = true;
      pageList(params).then((res) => {
        this.tableData = res.data;
        this.loading = false;
      });
    },
    statusFormat(row, column) {
      let str = "";
      this.statusList.map((item) => {
        if (item.id == row.currentStatus) {
          str = item.name;
        }
      });
      return str;
    },
    handleQuery() {
      this.getPage();
    },
    resetQuery() {
      // 保留当前选中的tab对应的菜单ID
      const currentMenuId = this.activityType;
      
      // 重置查询表单，只重置搜索相关参数
      this.queryParams = {
        activityName: "", // 清空活动名称
        activityMenuId: currentMenuId, // 保持当前选中的tab对应的菜单ID
        currentStatus: null // 清空状态选择
      };
      
      // 获取数据
      this.getPage();
    },
    onAdd() {
      this.dialogTitle = "新增";
      this.visible = true;
    },
    onDelete(id) {
      this.$confirm("你确定要删除活动内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteById(id).then(() => {
          this.getPage();
        });
      });
    },
    async onPublish(row) {
      this.form2.id = row.id;
      this.form2.nextEmp = null;
      this.nextEmpList = [];

      let res = await listUsers("kb", "reviewer_l1");
      if (res.code == 200) {
        this.nextEmpList = res.data;
      }

      this.open2 = true;
    },
    async firstSubmit() {
      if (this.form2.nextEmp == null) {
        this.$alert("请选择审核人！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        });
        return;
      }

      let nextEmpName = this.nextEmpList.filter(
        (item) => item.userId == this.form2.nextEmp
      )[0].userCnName;

      let res = await audit(this.form2.id, this.form2.nextEmp, nextEmpName);
      if (res.code == 200) {
        this.$modal.msgSuccess("提交一级审核成功！");
        this.open2 = false;
        this.getPage();
      }
    },
    onOffShelf(id) {
      this.$confirm("你确认要下架活动内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        offShelf(id).then(() => {
          this.getPage();
        });
      });
    },
    onEdit(id) {
      this.dialogTitle = "编辑";
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["AddForm"].onDetail(id);
      });
    },
    onDetail(id) {
      this.visibleDetail = true;
      this.$nextTick(() => {
        this.$refs["Detail"].onDetail(id);
      });
    },
    onSuccess() {
      this.visible = false;
      this.getPage();
    },
    onCancel() {
      this.visible = false;
    },
    onCancelDetail() {
      this.visibleDetail = false;
    },
    handleClick(tab) {
      // 保证tabName是字符串类型
      const tabName = String(tab.name);
      
      // 设置当前选中的选项卡ID
      this.activityType = tabName;
      this.queryParams.activityMenuId = tabName;
      
      // 如果不是互动体验标签页，加载对应的活动类型列表
      if (tabName !== "1") {
        this.loadActivityMenus(tabName);
      }
      
      // 获取数据
      this.getPage();
    },
    // 加载活动类型列表
    loadActivityMenus(parentId) {
      console.log('加载活动类型列表，parentId:', parentId);
      
      // 检查缓存中是否已有该parentId的数据
      if (this.activityMenuCache[parentId]) {
        console.log('使用缓存的活动类型列表');
        this.activityMenuList = this.activityMenuCache[parentId];
        return;
      }
      
      // 获取活动类型列表
      getListByParentId(parentId).then(res => {
        if (res.code === 200) {
          // 处理返回的rows数据，将menuName映射为label，id映射为value
          const menuList = (res.rows || []).map(item => ({
            label: item.menuName,
            value: item.id
          }));
          
          // 保存到缓存
          this.activityMenuCache[parentId] = menuList;
          this.activityMenuList = menuList;
          
          console.log('活动类型列表:', this.activityMenuList);
        } else {
          console.error('获取活动类型列表失败:', res.msg);
        }
      }).catch(error => {
        console.error('请求活动类型列表出错:', error);
      });
    },
    
    // 根据activityMenuId获取活动类型名称
    getActivityMenuName(menuId) {
      if (!menuId) return '未分类';
      
      // 如果activityMenuList已加载，直接查找
      if (this.activityMenuList && this.activityMenuList.length > 0) {
        const menu = this.activityMenuList.find(item => String(item.value) === String(menuId));
        if (menu) {
          return menu.label;
        }
      }
      
      // 如果是当前父级下的缓存，检查缓存
      if (this.activityMenuCache[this.activityType]) {
        const menu = this.activityMenuCache[this.activityType].find(
          item => String(item.value) === String(menuId)
        );
        if (menu) {
          return menu.label;
        }
      }
      
      // 如果未找到，返回ID
      return menuId;
    },
  },
};
</script>
